package cn.dakaqi.services.user.impl;

import cn.dakaqi.dao.user.VolunteerCertificationDao;
import cn.dakaqi.dao.user.VolunteerDao;
import cn.dakaqi.entities.user.Volunteer;
import cn.dakaqi.entities.user.VolunteerCertification;
import cn.dakaqi.services.user.VolunteerCertificationService;
import cn.dakaqi.utils.Clock;
import cn.dakaqi.utils.DKQConstant;
import cn.dakaqi.utils.DateUtil;
import cn.dakaqi.utils.Identities;
import cn.dakaqi.utils.exception.ServiceRuntimeException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * Created by chunyang on 2016/4/18.
 */
@Component(value = "volunteerCertificationService")
@Transactional
public class VolunteerCertificationServiceImpl implements VolunteerCertificationService
{
    @Autowired
    VolunteerCertificationDao volunteerCertificationDao;
    @Resource
    VolunteerDao volunteerDao;

    @Override
    public void save(String param) throws ServiceRuntimeException
    {
        JSONObject jsonObject = JSON.parseObject(param);
        VolunteerCertification volunteerCertification = JSON.toJavaObject(jsonObject, VolunteerCertification.class);
        volunteerCertification.setCrateTime(Clock.DEFAULT.getCurrentDate());
        if (StringUtils.isNotBlank(volunteerCertification.getResidenceAddress()))
        {
            String address[] = volunteerCertification.getResidenceAddress().split("-");
            if (address.length == 3)
            {
                String province = address[0];//省市
                String city = address[1];//城市
                String district = address[2];//区县
                volunteerCertification.setProvince(province);
                volunteerCertification.setCity(city);
                volunteerCertification.setDistrict(district);
            }
        }
        this.save(volunteerCertification);
    }

    @Override
    public void save(VolunteerCertification volunteerCertification) throws ServiceRuntimeException
    {
        //检查当前用户是否已实名认证了
        VolunteerCertification temp = findByMemberCode(volunteerCertification.getMemberCode());
        if (null != temp)
        {
            if (temp.getStatus() == DKQConstant.REAL_NAME_VERFIER_STATUS_APPLY)
                throw new ServiceRuntimeException("目前处于待审核状态");
            else
                throw new ServiceRuntimeException("已认证,不需要重复认证");
        }
        volunteerCertification.setStatus(DKQConstant.REAL_NAME_VERFIER_STATUS_APPLY);
        this.volunteerCertificationDao.save(volunteerCertification);
    }

    @Override
    public void updateStatus(String memberCode, int status, String verfierUser) throws ServiceRuntimeException
    {
        VolunteerCertification volunteerCertification = volunteerCertificationDao.findByMemberCode(memberCode);

        if (null != volunteerCertification)
        {
            volunteerCertification.setStatus(status);
            volunteerCertification.setVerifier(verfierUser);
            volunteerCertification.setVerifierTime(DateUtil.getToday());
            this.update(volunteerCertification);
            if (status == DKQConstant.REAL_NAME_VERFIER_STATUS_OK)
            {
                Volunteer volunteer = this.volunteerDao.findByMemberCode(volunteerCertification.getMemberCode());
                if (null != volunteer)
                {
                    volunteer.setMobile(volunteerCertification.getMobile());
                    volunteer.setRealName(volunteerCertification.getRealName());
                    volunteer.setProvince(volunteerCertification.getProvince());
                    volunteer.setCity(volunteerCertification.getCity());
                    volunteer.setDistrict(volunteerCertification.getDistrict());
                    volunteer.setCardType(volunteerCertification.getCardType());
                    volunteer.setCardNO(volunteerCertification.getCardNO());
                    volunteer.setResidenceAddress(volunteerCertification.getResidenceAddress());
                    volunteer.setJob(volunteerCertification.getJob());
                    volunteer.setServiceField(volunteerCertification.getServiceField());
                    volunteer.setSkill(volunteerCertification.getSkill());
                    volunteer.setLocked(DKQConstant.MEMBER_LOCK_1);
                    if (StringUtils.isNotBlank(volunteer.getProvince()))
                        volunteer.setVolunteerCode(createGroupCode(volunteer.getProvince(), "", ""));
                    else
                        volunteer.setVolunteerCode(createGroupCode("江苏省", "", ""));

                    this.volunteerDao.save(volunteer);
                }
            }
        } else
        {
            throw new ServiceRuntimeException("认证失败,当前数据无效");
        }
    }

    @Override
    public VolunteerCertification findOne(long id) throws ServiceRuntimeException
    {
        return this.volunteerCertificationDao.findOne(id);
    }

    @Override
    public VolunteerCertification findByMemberCode(String memberCode) throws ServiceRuntimeException
    {
        Map<String, SearchFilter> filters = Maps.newHashMap();
        filters.put("memberCode", new SearchFilter("memberCode", SearchFilter.Operator.EQ, memberCode));
        Specification<VolunteerCertification> spec = DynamicSpecifications.bySearchFilter(filters.values(), VolunteerCertification.class);
        List<VolunteerCertification> list = volunteerCertificationDao.findAll(spec);
        if (null == list || list.size() == 0)
            return null;
        else
            return list.get(0);
    }

    @Override
    public void update(String param) throws ServiceRuntimeException
    {
        JSONObject jsonObject = JSON.parseObject(param);
        VolunteerCertification volunteerCertification = JSON.toJavaObject(jsonObject, VolunteerCertification.class);
        volunteerCertification.setCrateTime(Clock.DEFAULT.getCurrentDate());
        if (StringUtils.isNotBlank(volunteerCertification.getResidenceAddress()))
        {
            String address[] = volunteerCertification.getResidenceAddress().split("-");
            String province = address[0];//省市
            String city = address[1];//城市
            String district = address[2];//区县
            volunteerCertification.setProvince(province);
            volunteerCertification.setCity(city);
            volunteerCertification.setDistrict(district);
        }

        VolunteerCertification target = findByMemberCode(volunteerCertification.getMemberCode());
        BeanUtils.copyProperties(volunteerCertification, target);
        target.setStatus(DKQConstant.REAL_NAME_VERFIER_STATUS_APPLY);
        update(target);
    }

    @Override
    public void update(VolunteerCertification volunteerCertification) throws ServiceRuntimeException
    {
        volunteerCertificationDao.save(volunteerCertification);
    }
    private String createGroupCode(String province,String city,String district)
    {
        StringBuffer sb = new StringBuffer();
        province = "江苏省";
        String code = this.volunteerDao.queryProvinceCode(province);
        sb.append("V");
        sb.append(code);
        sb.append(DateUtil.currentDateStringTrim());
        String targetStr[] = Identities.uuid().split("-");
        sb.append(targetStr[1].toUpperCase());
        return sb.toString();
    }
}
